/*
  Copyright 2002 Ronald S. Burkey

  This file is part of GutenMark.

  GutenMark is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  GutenMark is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with GutenMark; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  Filename:	AddTocToLatex.c
  Purpose:	Versions of GutenMark through today did not add a table
  		of contents to LaTeX output (because I didn't know how to
		do it).  Therefore, LaTeX created through today doesn't have
		any table of contents.  This utility adds a table of
		contents to an existing LaTeX file as created by GutenMark.
  Mods:		08/06/02 RSB	Began.

  Usages:  Accepts a latex file on the standard input, and writes a
  modified file on the standard output.
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define BUFSIZE 2048
static char Buffer[BUFSIZE + 1];

int
main (void)
{
  int BraceCount, PrefatoryFound = 0;
  char *s, *ss, *LineType;
  Buffer[BUFSIZE] = 0;
  while (NULL != fgets (Buffer, BUFSIZE, stdin))
    {
      if (!strcmp (Buffer, "\\chapter*{Prefatory Materials}\n"))
        PrefatoryFound = 1;
      else if (PrefatoryFound == 1 &&
               !strncmp (Buffer, "\\chapter*{", 10))
        {
          fputs ("\\mainmatter\n", stdout);
          PrefatoryFound = 2;
        }
      fputs (Buffer, stdout);
      if (!strncmp (Buffer, "\\maketitle", 10))
        {
	  fputs ("\\frontmatter\n", stdout);
	  fputs ("\\tableofcontents\n", stdout);
	  fputs ("\\newpage\n", stdout);
	  continue;
	}
      if (!strncmp (Buffer, "\\chapter*{", 10) && PrefatoryFound != 1)
        LineType = "\\addcontentsline{toc}{chapter}";
      else if (!strncmp (Buffer, "\\section*{", 10))
        LineType = "\\addcontentsline{toc}{section}";
      else 
        LineType = NULL;
      if (LineType != NULL)
        {
	  s = &Buffer[10];
	  if (!strncmp (s, "\\protect\\raggedright ", 21))
	    s += 21;
	  for (ss = s, BraceCount = 1; *ss; ss++)
	    {
	      if (*ss == '{')
	        BraceCount++;
	      else if (*ss == '}')
	        {
		  BraceCount--;
		  if (BraceCount == 0)
		    {
		      *ss = 0;
		      while (ss[-1] == ' ')
			*(--ss) = 0;
		      fprintf (stdout,
		               "%s{%s}\n",
			       LineType, s);
		      break;
		    }
		}

	    }
	}
    }
  return (0);
}

